//
//  StoreDynamicDetailViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/30.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "GKPhotoBrowser.h"

#import "MediaBannerTableviewCell.h"

#import "StoreDetailNaviView.h"
#import "StoreDynamicBannerCell.h"
#import "StoreDynamicTextCell.h"
#import "StoreDynamicStoreCell.h"
#import "CommonDynamicModel.h"
#import "CommonSellerModule.h"
#import "StoreDetailViewController.h"
#import "MessageCenterViewController.h"
#import "StoreHotelDetailViewController.h"
#import "StoreDynamicDetailViewController.h"

@interface StoreDynamicDetailViewController ()<UITableViewDelegate, UITableViewDataSource,SDCycleScrollViewDelegate,GKPhotoBrowserDelegate>

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) MediaBannerTableviewCell *mediaCell;


@property (nonatomic, strong) CommonDynamicModel *model;

@property (nonatomic, strong) CommonSellerModule *storeModel;

@property (nonatomic, strong) StoreDetailNaviView *naviView;

@property (nonatomic, strong) NSMutableArray *bannerImageUrls;



@end

@implementation StoreDynamicDetailViewController

- (void)dealloc {
    [self.mediaCell pause];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.mediaCell pause];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self request_DynamicDetail];
}

- (void)initView {
    
    //屏幕常亮
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    self.navigationController.navigationBarHidden = YES;
    #if RT_INTERACTIVE_PUSH
        self.rt_navigationController.rt_enableInteractivePush = YES;
    #endif
    
    WEAKSELF
    [RACObserve([TT_MessageManager manager], totalUnReadCount) subscribeNext:^(id x) {
        if ([TT_MessageManager manager].totalUnReadCount > 0) {
            weakSelf.naviView.msgBtn.badgeValue = [NSString stringWithFormat:@"%d",[TT_MessageManager manager].totalUnReadCount];
            weakSelf.naviView.msgBtn.badgeBGColor = [UIColor redColor];
        } else {
            weakSelf.naviView.msgBtn.badgeValue = @"";
            weakSelf.naviView.msgBtn.badgeBGColor = [UIColor clearColor];
        }
    }];

    if([self.tableview respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        if (@available(iOS 11.0, *)) {
            self.tableview.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
    }
    
    self.title = @"动态详情";
    [self.view addSubview:self.tableview];
    [self.view addSubview:self.naviView];

    [self.naviView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(kStatusBarHeight + NavBar_Height);
    }];

    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.top.mas_equalTo(0);

    }];
    
    self.naviView.StoreDetailNaviViewBlock = ^(StoreDetailNaviViewActionType actionType) {
        
        switch (actionType) {
            case StoreDetailNaviViewActionType_back:{
                [weakSelf goBack];
            } break;
            case StoreDetailNaviViewActionType_favor:{

            } break;
            case StoreDetailNaviViewActionType_share:{

                [weakSelf openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {
                    if (isLogin) {
                        [weakSelf share];
                    }
                }];

            } break;
            case StoreDetailNaviViewActionType_im:{

                MessageCenterViewController *vc = [[MessageCenterViewController alloc] init];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            } break;
            default:
                break;
        }
    };
}

- (void)showImageWithArray:(NSArray *)imageUrls index:(NSInteger)index {
    NSMutableArray *photos = [NSMutableArray new];
    
    [imageUrls enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        GKPhoto *photo = [GKPhoto new];
        photo.url = [NSURL URLWithString:obj];
        [photos addObject:photo];
    }];
    
    GKPhotoBrowser *browser = [GKPhotoBrowser photoBrowserWithPhotos:photos currentIndex:index];
    browser.showStyle = GKPhotoBrowserShowStyleNone;
    browser.hideStyle = GKPhotoBrowserHideStyleZoomScale;
    
    browser.delegate  = self;
    [browser showFromVC:self];
}

#pragma mark Share
- (void)share {
    CommonShareModel *model = [[CommonShareModel alloc] init];
    model.url = [NSString stringWithFormat:@"%@%@?sdyId=%@&myCode=%@",BA_GlobalH5_Domain,@"/shopDynamicDetail",self.sdyId,[TTUserModel sharedObject].myCode];
    model.title = self.model.sdyTitle;
    model.content = @"婚前婚后邀您体验";
    
    if (self.bannerImageUrls.count > 0) {
        model.image = self.bannerImageUrls.firstObject;
    }
    [[TT_ShareManager share] callShareViewWithModel:model];
}

- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.row) {
        case ProductDetailCellType_Banner:{
            return TTScreenWidth;
        } break;
        case StoreDynamicDetailCellType_Text:{
            return [StoreDynamicTextCell calculateHeightWithModel:self.model];
        } break;
        case StoreDynamicDetailCellType_StoreInfo:{
            return 100;
        } break;
        default:
            break;
    }
    return CGFLOAT_MIN;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WEAKSELF
    switch (indexPath.row) {
        case ProductDetailCellType_Banner:{

            self.mediaCell = [tableView dequeueReusableCellWithIdentifier:@"MediaBannerTableviewCellID"];
            self.mediaCell.selectionStyle =UITableViewCellSelectionStyleNone;

            [self.mediaCell fillWithImgArray:self.bannerImageUrls.mutableCopy AndVideoUrl:self.model.videoModel.url];
            
            self.mediaCell.bannerIndexClicked = ^(NSInteger index) {
                if (weakSelf.bannerImageUrls.count > 0) {
                    [weakSelf showImageWithArray:weakSelf.bannerImageUrls index:index];
                }
            };
            
            return self.mediaCell;

        } break;
        case StoreDynamicDetailCellType_Text:{
            
            StoreDynamicTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StoreDynamicTextCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            [cell fillCellWithModel:self.model];
            return cell;
            
        } break;
        case StoreDynamicDetailCellType_StoreInfo:{
            
            StoreDynamicStoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StoreDynamicStoreCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            [cell fillCellWithModel:self.storeModel];
            return cell;
            
        } break;
        default:
            break;
    }
    
    StoreDynamicBannerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StoreDynamicBannerCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.row) {
        case ProductDetailCellType_Banner:{

        } break;
        case StoreDynamicDetailCellType_Text:{

        } break;
        case StoreDynamicDetailCellType_StoreInfo:{

            if ([self.storeModel.classId isEqualToString:Store_Category_Hotel]) {
                
                StoreHotelDetailViewController *vc = [[StoreHotelDetailViewController alloc] init];
                vc.storeId = self.storeModel.sellerId;
                [self.navigationController pushViewController:vc animated:YES];
                
            } else {
                StoreDetailViewController *vc = [[StoreDetailViewController alloc] init];
                vc.storeId = self.storeModel.sellerId;
                [self.navigationController pushViewController:vc animated:YES];
            }
        } break;
        default:
            break;
    }
    
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerClass:[MediaBannerTableviewCell class] forCellReuseIdentifier:@"MediaBannerTableviewCellID"];
        [_tableview registerNib:[UINib nibWithNibName:@"StoreDynamicTextCell" bundle:nil] forCellReuseIdentifier:@"StoreDynamicTextCellID"];
        [_tableview registerNib:[UINib nibWithNibName:@"StoreDynamicStoreCell" bundle:nil] forCellReuseIdentifier:@"StoreDynamicStoreCellID"];
    }
    return _tableview;
}

- (StoreDetailNaviView *)naviView {
    
    if (!_naviView) {
        _naviView = [[NSBundle mainBundle] loadNibNamed:@"StoreDetailNaviView"owner:nil options:nil].firstObject;
        _naviView.favoriteBtn.hidden = YES;
    }
    return _naviView;
}

- (CommonDynamicModel *)model {
    if (!_model) {
        _model = [[CommonDynamicModel alloc] init];
    }
    return _model;
}

- (CommonSellerModule *)storeModel {
    if (!_storeModel) {
        _storeModel = [[CommonSellerModule alloc] init];
    }
    return _storeModel;
}


- (void)request_DynamicDetail {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:@(1) forKey:@"pageNum"];
    [dic setValue:@(1) forKey:@"pageSize"];
    
    NSDictionary *t = @{}.mutableCopy;
    [t setValue:self.sdyId forKey:@"sdyId"];
    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_StoreDynamic];
    
    [SVProgressHUD showWithStatus:@"正在加载"];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *SellerDynamicList = [resultDic valueForKey:@"SellerDynamicList"];
                NSDictionary *seller = [resultDic valueForKey:@"seller"];

                weakSelf.storeModel = [CommonSellerModule modelWithDictionary:seller];
                
                if ([SellerDynamicList isKindOfClass:[NSArray class]]) {
                    
                    if (SellerDynamicList.count > 0) {
                        NSDictionary *SellerDynamicListDic = SellerDynamicList.firstObject;
                        if ([SellerDynamicListDic isKindOfClass:[NSDictionary class]]) {
                            CommonDynamicModel *dynamicModel = [CommonDynamicModel modelWithDictionary:SellerDynamicListDic];
                            
                            NSArray *imageUrls = [SellerDynamicListDic valueForKey:@"imageUrls"];
                            
                            if ([imageUrls isKindOfClass:[NSArray class]]) {
                                dynamicModel.imageUrls = @[].mutableCopy;
                                weakSelf.bannerImageUrls = @[].mutableCopy;
                                for (int i = 0; i < imageUrls.count; i ++) {
                                    NSDictionary *imgDic = imageUrls[i];
                                    CommonImageModel *imgModel = [CommonImageModel modelWithDictionary:imgDic];
                                    
                                    if ([imgModel.type isEqualToString:@"dtvideo"]) {
                                        dynamicModel.videoModel = [[CommonImageModel alloc] init];
                                        dynamicModel.videoModel = imgModel;
                                    } else {
                                        if (imgModel.url.length > 0) {
                                            [weakSelf.bannerImageUrls addObject:imgModel.url];
                                        }
                                    }
                                    
                                    [dynamicModel.imageUrls addObject:imgModel];
                                }
                            }
                            weakSelf.model = dynamicModel;
                        }
                    }
                }

                [weakSelf initView];
                [weakSelf.tableview reloadData];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
    }];
    
}



@end
